/*
 * @Author: sunzhijun 
 * @Date: 2019-10-31 16:43:57 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-04-01 10:09:18
 */
import CommonAction from './common';
import { formDownload, cacheTools, ajax } from 'nc-lightapp-front';
import do_print from 'src/hrpub/common/utils/print';
import Export from 'src/hrpub/common/utils/exportHtml';
import {saveValidate } from 'src/hrpub/common/utils/utils';
import { getAppPageConfig } from 'src/hrpub/common/utils/utils';

export default class HeaderAction extends CommonAction {
    constructor(comp) {
        super();
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
        this.config = getAppPageConfig();
    }

    //变更组织
    changeOrg = async (org)=>{
        const { action } = this.comp;
        await this.dispatch({
            type: 'main/update',
            payload: {
                orgValue: org,
                pk_org: org.refpk
            }
        })
        if(!org.refpk){
            action.btnAct.noneOrgButtonStatus();
        }else {
            action.btnAct.orgButtonStatus();
            action.tableAct.getTableData();
        }
    }

    // 选择单据范围
    // 获取选择范围状态列表内容
    getOrderStatusList = () =>{
        let { props: { main: { language} } } = this.comp;
        let orderStatusList = [{
                key: 'all',
                label: language['hrcm-000052'], // 全部
            }, {
                key: '-1',
                label: language['hrcm-000053'], // '自由态'
            }, {
                key: '3',
                label: language['hrcm-000054'], // 提交
            }, {
                key: '2',
                label: language['hrcm-000055'], // 审批进行中
            }, {
                key: '1',
                label: language['hrcm-000056'], // 审批通过
            }, {
                key: '0',
                label: language['hrcm-000057'], // 审批未通过
            }
        ]
        return orderStatusList;
    }
    // 获取选择范围时间列表内容
    getTimeRangeList = ()=>{
        let { props: { main: { language} } } = this.comp;
        let timeRangeList = {
            'oneWeek': language['hrcm-000058'], // 一周内
            'oneMonth': language['hrcm-000059'], // 一个月内
            'threeMonth': language['hrcm-000060'], // 三个月内
            'custom': language['hrcm-000061'], // 自定义
        }
        return timeRangeList;
    }
    
    // 头部筛选框选择单据状态
    changeOrderStatus = async (value, status) =>{
        let selectVal = [];
        if( status.includes('all') && value.length > 1){
            value.map((item, index)=>{
                if(item !== 'all'){
                    selectVal.push(item)
                }
            })
            await this.dispatch({
                type: 'main/update',
                payload: {
                    orderStatus: selectVal
                }
            })
            this.combileChangeOrder();
        }else{
            if(value.includes('all')){
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        orderStatus: ['all']
                    }
                })
                this.combileChangeOrder();
            }else{
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        orderStatus: value
                    }
                })
                this.combileChangeOrder();
            }
        }
    }
    // 头部筛选框选择单据时间范围
    changeOrderRange  = async (range) => {
        const { props } = this.comp;
        const { main } = props;
        let { time, orderStatus } = main;
        time.beginTime = '';
        time.endTime = '';
        if( range === 'custom' ){
            time.time = '';
        }else{
            time.time = range;
        }
        await this.dispatch({
            type: 'main/update',
            payload: {
                timeRange: range,
                timerRangeValue: [],
                time
            }
        })
        range !== 'custom' ? this.combileChangeOrder() : null;
    }

    // 头部筛选框选择单据时间自定义范围
    // "beginTime":"","billstate":"-1,3","endTime":"","time":"threeMonth"}
    changeOrderTime = async ( times ) =>{
        const { props } = this.comp;
        const { main } = props;
        let { time, orderStatus } = main;
        time.billStatus = orderStatus;
        time.beginTime = times[0];
        time.endTime = times[1];
        await this.dispatch({
            type: 'main/update',
            payload: {
                timerRangeValue: times,
                time
            }
        })
        this.combileChangeOrder();
    }

    // 头部筛选选择单据结合调用
    combileChangeOrder = () =>{
        const { action, props } = this.comp;
        const { main } = props;
        let { orderStatus, time, pk_org } = main;
        let selectObj = [], obj;
        time.billStatus = orderStatus;
        orderStatus.map((item, index)=>{
            obj =  {
                "field":"sign_state",
                "value":{
                    "firstvalue": "1",
                    "secondvalue": ""
                }
            }
            console.log(item, index);
            obj.value.firstvalue = item;
            selectObj.push(obj);
        });
        let conditions = {
            "querycondition":{
                "logic":"and",
                "conditions": selectObj
            },
            "nctz":8
        }
        let allSelect = {};
        Object.assign(allSelect, conditions, time);
        action.tableAct.getTableData('', allSelect);
    }

    // 新增
    newAddAction = ()=>{
        this.dispatch({
            type: 'main/update',
            payload: {
                setModalVisible: true
            }
        })
    }

    //返回
    back = async ()=>{
        const { props: { main }, action } = this.comp;
        let { isEdit } = main;
        if( isEdit ){ //编辑态返回
            this.cancelAction();
        }else{//浏览态返回
            await this.dispatch({
                type: 'main/update',
                payload: {
                    isCardForm: false,
                    isShowOrg: true,
                    isCardPaginationVisible: false
                }
            })
            action.btnAct.orgButtonStatus();
            action.tableAct.getTableData();
        }
    }

    //取消
    cancelAction = ()=>{
        let { props: { main: { language } } } = this.comp;
        this.promptBox({
            color: 'warning', 
            title: language['hrcm-000067'] /*国际化：请注意！*/,
            content: language['hrcm-000022'] /*国际化：是否确定要取消？*/,
            beSureBtnClick: this.cancelFn
        })
    }
    //取消Function
    cancelFn = async ()=>{
        const { props: { form, main }, action } = this.comp;
        let { cardId } = main;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isEdit: false,
                isCardPaginationVisible: true,
                isModifyEdit: false
            }
        })
        form.setFormStatus(cardId, 'browse');
        action.btnAct.cancelEditBUttonStatus();
        action.cardAct.getFormData();
    }

    //修改单据后保存
    saveAction = async ()=>{
        const { props, action } = this.comp;
        const { form, main } = props;
        let { cardId, fromApprove, step, info2, pageid, language } = main;
        console.log(cardId,props,form)
        // if (!form.isCheckNow( [cardId], 'warning')) {
        //     return false
        // }
        // saveValidate(props, pageid, 'dataBase', ['dataBefore', 'dataAfter'] , 'extcard').then( async () => {
            let allFormValues = form.getAllFormValue(cardId).rows[0].values;
            let afterFormValues = {};
            for (let key in allFormValues) {
                if (key.indexOf('_old') === -1) {
                    afterFormValues[key] = allFormValues[key]
                }
            }
            let dataObj = {
                baseParam: {step: step, pageType: 'card', info2: info2},
                scene : fromApprove ? 'approvesce' : null,
                formData: {
                    model: {
                        rows: [
                            {
                                values: afterFormValues,
                                status: '1'
                            }
                        ]
                    }
                }
            }
            let res = await this.dispatch({
                type: 'main/saveDataAction',
                payload: {
                    ...dataObj
                }
            });
            if( res.success ){
                this.toast({
                    color: 'success',
                    content:  language['hrcm-000045']// 保存成功
                });
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        isEdit: false,
                        isCardPaginationVisible: true,
                        isModifyEdit: false,
                        cardPaginationStatus: 1
                    }
                })
                form.setFormStatus(cardId, 'browse');
                action.btnAct.cancelEditBUttonStatus();
                action.cardAct.getFormData();
            }
        // })
    }

    //发起
    // aunchAction = ()=>{

    // }

    // 打开查询
    query = () => {
        const {props: { main, meta, search }} = this.comp;
        let { pk_org } = main;
        let template = meta.getMeta();
        template["listquery"].items.map(item => {
             // 部门
             if (item.attrcode === 'pk_psnjob.pk_dept') {
                item.queryCondition = () => {
                    return {
                        'pk_hrorg': pk_org
                    }
                }
             }else if(item.attrcode === 'pk_conttext'){
                item.queryCondition = {
                    pk_org: pk_org,
                    GridRefActionExt: 'nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder'
                }
            }
        })
        
        meta.setMeta(template, () => {
            search.openAdvSearch('listquery', true);
        })
    }

    // 查询数据
    searchData = () => {
        const {props, action} = this.comp;
        const {dispatch, search} = props;
        let getConditions = search.getQueryInfo('listquery', true);
        this.dispatch({
            type: 'main/update',
            payload: {
                conditions: getConditions,
                oid: getConditions.oid
            }
        })
        action.tableAct.getTableData('',getConditions);
    }

    //编辑
    editAction = ()=>{
        const { props: { form, main }, action } = this.comp;
        let { cardId } = main;
        this.dispatch({
            type: 'main/update',
            payload: {
                isCardPaginationVisible: false,
                isEdit: true
            }
        })
        action.btnAct.editButtonStatus();
        form.setFormStatus(cardId, 'edit');
    }

    //修改
    modifyAction = async ( record )=>{
        const { action } = this.comp;
        await this.dispatch({
            type: 'main/update',
            payload: {
                isModifyEdit: true
            }
        })
        await action.tableAct.toCardForm(record);
        this.editAction();
    }

    //流程历史
    historyAction = ( record )=>{
        const { props: { form, main } } = this.comp;
        let { cardId } = main;
        let billid, billtype;
        if( !!record ){
            billid = record.values.pk_ctrtmng.value;
            billtype = record.values.pk_billtype.value;
        }else {
            billid = form.getFormItemsValue(cardId,'pk_ctrtmng').value;
            billtype = form.getFormItemsValue(cardId,'pk_billtype').value;
        }
        this.dispatch({
            type: 'main/update',
            payload: {
                billtype: billtype,
                billid: billid,
                showFlowModal: true
            }
        })
    }

    //关闭流程历史
    closeApproveDetailModal = ()=>{
        this.dispatch({
            type: 'main/update',
            payload: {
                showFlowModal: false
            }
        })
    }

    //删除
    deleteAction = ( record )=>{
        let { props: { main: { language } } } = this.comp;
        let pk_ctrtmngs = this.getPkCtrtmng( record );
        if( pk_ctrtmngs && !!pk_ctrtmngs.length ){
            this.operationCheckout(pk_ctrtmngs, 'delete').then(()=>{
                this.deleteHint( pk_ctrtmngs );
            });
        }else{
            this.toast({color: 'warning', content: language['hrcm-000068']}); /*国际化：请选择要操作的记录！*/
        }
    }

    // 是否确定删除
    deleteHint = ( pk_ctrtmngs )=>{
        let { props: { main: { language } } } = this.comp;
        this.promptBox({
            color: 'warning', 
            title: language['hrcm-000067'],     /*国际化：请注意！ */
            content: language['hrcm-000021'],   /*国际化：您确定要删除所选数据吗?*/
            beSureBtnClick: ()=> this.deleteFn(pk_ctrtmngs)
        })
    }

    //删除Function
    deleteFn = async (pk_ctrtmngs)=>{
        const { props: { main, cardPagination }, action } = this.comp;
        let { pk_org, appConfig, isCardForm, pk_ctrtmng, language } = main;
        let res = await this.dispatch({
            type: 'main/deleteAction',
            payload: {
                pk_ctrtmngs: pk_ctrtmngs,
                pk_org: pk_org,
                appCode: appConfig.appcode
            }
        });
        // debugger
        if(res.success){
            this.toast({color: 'success', content: language['hrcm-000046']}); /*国际化：删除成功！*/
            if( isCardForm ){
                let allpks= cacheTools.get('allpks');
                let deleteIndex = allpks.findIndex(value => value === pk_ctrtmngs);
                allpks.splice(deleteIndex, 1);
                let allpksLen = allpks.length;
                let nextPk_ctrtmng;
                if( allpksLen > deleteIndex ){
                    nextPk_ctrtmng = allpks[deleteIndex]
                }else{
                    nextPk_ctrtmng = allpks[deleteIndex - 1]
                }
                cacheTools.set('allpks', allpks);
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        pk_ctrtmng : nextPk_ctrtmng || '',
                        cardPaginationStatus: 3
                    }
                })
                action.cardAct.getFormData();
            }else{
                action.tableAct.getTableData();
            }
        }
    }

    //撤回
    revokeAction = ( record )=>{
        let { props: { main: { language } } } = this.comp;
        let pk_ctrtmngs = this.getPkCtrtmng( record );
        if( !!pk_ctrtmngs.length ){
            this.operationCheckout(pk_ctrtmngs, 'revoke').then(()=>{
                this.revokeFn(pk_ctrtmngs)
            });
        }else{
            this.toast({color: 'warning', content: language['hrcm-000068']}); /*国际化：请选择要操作的记录！ */
        }
    }

    //撤回Function
    revokeFn = async (pk_ctrtmngs)=>{
        const { props: { main }, action } = this.comp;
        let { pk_org, appConfig, isCardForm, language } = main;
        let res = await this.dispatch({
            type: 'main/revokeAction',
            payload: {
                pk_ctrtmngs: pk_ctrtmngs,
                pk_org: pk_org,
                appCode: appConfig.appcode
            }
        });
        if(res.success){
            this.toast({color: 'success', content: language['hrcm-000065']}); /*国际化：撤回成功！*/
            if( isCardForm ){
                action.cardAct.getFormData();
            }else{
                action.tableAct.getTableData();
            }
        }
    }

    //提交
    submitAction = ( record )=>{
        let { props: { main: { language } } } = this.comp;
        let pk_ctrtmngs = this.getPkCtrtmng( record );
        if( !!pk_ctrtmngs.length ){
            this.operationCheckout(pk_ctrtmngs, 'submit').then(()=>{
                this.submitFn(pk_ctrtmngs)
            });
        }else{
            this.toast({color: 'warning', content: language['hrcm-000068']}); /*国际化：请选择要操作的记录！ */
        }
    }

    //判断选中的主键值
    getPkCtrtmng = ( record )=>{
        const { props } = this.comp;
        const { editTable: { getCheckedRows }, main, form } = props;
        let { tableId, isCardForm, cardId } = main;
        let pk_ctrtmngs = [];
        if( isCardForm ){ //卡片界面获取主键
            pk_ctrtmngs = form.getFormItemsValue(cardId,'pk_ctrtmng').value;
        }else{//列表界面获取主键
            if( !!record ){
                let pk_ctrtmng = record.values.pk_ctrtmng.value;
                pk_ctrtmngs.push(pk_ctrtmng);
            }else{
                let pk_ctrtmngArr = getCheckedRows(tableId);
                !!pk_ctrtmngArr.length && pk_ctrtmngArr.map(( item )=>{
                    let pk_ctrtmngData = item.data.values.pk_ctrtmng.value;
                    pk_ctrtmngs.push(pk_ctrtmngData);
                })
            }
        }
        this.dispatch({
            type: 'main/update',
            payload: {
                pk_ctrtmng: pk_ctrtmngs
            }
        })
        return pk_ctrtmngs;
    }
    
    //提交Function
    submitFn = async (pk_ctrtmngs, designateData = null)=>{
        const { props: { main }, action } = this.comp;
        let { pk_org, appConfig, isCardForm, language } = main;
        let res = await this.dispatch({
            type: 'main/submitAction',
            payload: {
                pk_ctrtmngs: pk_ctrtmngs,
                pk_org: pk_org,
                appCode: appConfig.appcode,
                ...designateData
            }
        });
        if(res.success){
            if (res.data && res.data.content) {
                this.dispatch({
                    type: 'main/update',
                    payload: {
                        designateDisplay: true,
                        designateData: res.data.content,
                        cache_pk_ctrtmngs: pk_ctrtmngs
                    }
                })
                return;
            }else{
                this.toast({color: 'success', content: language['hrcm-000050']}); /*国际化：提交成功！*/
                this.hideDesignate();
            }
            if( isCardForm ){
                action.cardAct.getFormData();
            }else{
                action.tableAct.getTableData();
            }
        }
    }

    //如果有指派调用此方法
    submitDesignate = (value)=>{
        const { props: { main } } = this.comp;
        let { cache_pk_ctrtmngs } = main;
        let designateData = {
            content: value
        }
        this.submitFn(cache_pk_ctrtmngs, designateData);
    }

    //关闭指派
    hideDesignate = ()=>{
        this.dispatch({
            type: 'main/update',
            payload: {
                designateDisplay: false
            }
        })
    }

    //刷新
    refreshAction = ()=>{
        const { props: { main }, action } = this.comp;
        let { isCardForm } = main;
        if( isCardForm ){
            action.cardAct.getFormData('refresh');
        }else{
            action.tableAct.getTableData('refresh');
        }
    }

    //公示
    publicecityAction = ()=>{
        window.top.openNew({appcode: '60654090'});
    }

    //操作校验
    operationCheckout = ( billPks, opFlag )=>{
        const { props: { main }, action } = this.comp;
        let { appConfig } = main;
        return new Promise( async (reslove, reject)=>{
            let res = await this.dispatch({
                type: 'main/operationCheckout',
                payload: {
                    appCode: appConfig.appcode,             //应用编码
                    billPks: billPks,                       //操作数据主键数据
                    opFlag: opFlag                          //操作编码（和之前合同那块参数类似
                }
            });
            if( res.success ){
                // debugger
                reslove('成功');
            }
        })
    }

    //设置卡片翻页
    setCardPagination = (pk_ctrtmng)=> {
        const { props } = this.comp;
        const { cardPagination, main } = props;
        let { cardPaginationStatus } = main;
        if( Array.isArray(pk_ctrtmng) ){
            pk_ctrtmng = pk_ctrtmng.toString();
        }
        cardPagination.getNextCardPaginationId({id: pk_ctrtmng});
        cardPagination.setCardPaginationId({id: pk_ctrtmng , status: 1});
    }

    //操作卡片翻页
    handlePageChange = async ( props, id )=>{
        const { action } = this.comp;
        await this.dispatch({
            type: 'main/update',
            payload: {
                pk_ctrtmng: id
            }
        })
        action.cardAct.getFormData()
    }

    //导出模板
    export_excelAction = ()=>{
        formDownload({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngExportTempletAction.do',
            enctype: 2
        })
    }

    //打印
    printAction = ()=>{
        const { props } = this.comp;
        const { editTable, meta, main } = props;
        let { titleName, tableId, language } = main;
        let allTableList = editTable.getAllRows(tableId);
        let template = meta.getMeta()[tableId];
        let len = template.items.length;
        template.items.splice(len-1,1);
        do_print(document.querySelector('#hot-key-dataList'), {
            title: titleName,
            maker: language['hrcm-000004'] /*国际化：制单人*/,
            date: language['hrcm-000005'] /*国际化：制表日期*/,
            // beforeAppend: (data) => {
                // data[1].map((item, index) => {
                //     debugger
                //     let len = item && item.length;
                //     item.splice(len-1, 1);
                // });
                // return data;
            // }
        },{
            data: allTableList,
            tableTmp: template
        })
    }

    //输出
    outputAction = ()=>{
        const { props } = this.comp;
        const { editTable, meta, main } = props;
        let { titleName, tableId, language } = main;
        Export(document.querySelector('.u-table-scroll'),
        {
            title: titleName /* 国际化处理： 合同变更申请*/,
            fileName: titleName + language['hrcm-000002'] /* 国际化处理： 合同变更申请数据*/,
            maker: language['hrcm-000004'] /*国际化：制单人*/,
            date: language['hrcm-000005'] /*国际化：制表日期*/,
        }, {
            data: editTable.getAllData(tableId).rows,
            meta: meta.getMeta()[tableId],
            showIndex: false
        });
    }

    FileManagement (rowRecord) {
        const {props} = this.comp;
        const {main, dispatch} = props;
      let pk_ctrtmng = ''
      if (!main.isCardForm) {
          pk_ctrtmng = rowRecord.values.pk_ctrtmng.value
      } else {
          pk_ctrtmng = main.formData.rows[0].values.pk_ctrtmng.value
      }
      main.nodeRefs.fileUpload.showUploader(pk_ctrtmng)
  }

    // 联查卡片
    showCardview = ()=>{
        const {props:{ form, main }} = this.comp;
        let { cardId, nodeRefs } = main;
        let formData = form.getAllFormValue(cardId).rows;
        // nodeRefs.showCardViewRefs.openCardViewModal(formData);
        nodeRefs.wpsview.openView(formData)
    }
}

